package com.demo.core.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.base.model.InvitationCode;
import com.demo.base.model.WebUserForCompany;
import com.demo.base.model.WebUserForPerson;
import com.demo.base.pojo.TempVo;
import com.demo.base.util.CommonUtil;
import com.demo.base.util.DateTimeUtil;
import com.demo.base.util.Encodes;
import com.demo.base.util.PinyinToolkit;
import com.demo.base.util.RequestContextHolderUtil;
import com.demo.base.util.StringUtil;
import com.demo.core.service.InvitationCodeService;
import com.demo.core.service.PhoneMsgService;
import com.demo.core.service.WebService;
import com.demo.core.service.WebUserForCompanyService;
import com.demo.core.service.WebUserForPersonService;

@RequestMapping("/web")
@Controller
public class WebController {

	@Autowired
	private WebUserForPersonService webUserForPersonService;
	
	@Autowired
	private WebUserForCompanyService webUserForCompanyService;
	
	@Autowired
	private PhoneMsgService phoneMsgService;
	
	@Autowired
	private WebService webService;
	
	@Autowired
	private InvitationCodeService invitationCodeService;
	
	/**
	 * 网站用户登录（个人）
	 * @param webUserForPerson
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/loginForPerson")
	public Map<String,Object> loginForPerson(@RequestBody WebUserForPerson webUserForPerson){
		
		Map<String,Object> map = new HashMap<String,Object>();
		//判断登录名或密码是否为空
		if(CommonUtil.isNull(webUserForPerson.getLoginName()) || CommonUtil.isNull(webUserForPerson.getPassword())){
			map.put("status", CommonUtil.ERROR);
			map.put("message", "用户名或密码不能为空！");
			return map;
		}
		
		webUserForPerson = webUserForPersonService.authWebUserForPerson(webUserForPerson.getLoginName(), Encodes.encodeMd5(webUserForPerson.getPassword()));
		
		//判断该用户是否为空
		if(CommonUtil.isNull(webUserForPerson)){
			map.put("status", CommonUtil.FAIL);
			map.put("message", "用户不存在，请检查用户名和密码再登录!");
		}else{
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "登录成功");
			map.put("data", webUserForPerson);
		}
		
		return map;	
	}
	
	/**
	 * 网站用户登录（企业）
	 * @param webUserForCompany
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/loginForCompany")
	public Map<String,Object> loginForCompany(@RequestBody WebUserForCompany webUserForCompany){
		
		Map<String,Object> map = new HashMap<String,Object>();
		//判断登录名或密码是否为空
		if(CommonUtil.isNull(webUserForCompany.getLoginName()) || CommonUtil.isNull(webUserForCompany.getPassword())){
			map.put("status", CommonUtil.ERROR);
			map.put("message", "用户名或密码不能为空！");
			return map;
		}
		
		webUserForCompany = webUserForCompanyService.authWebUserForCompany(webUserForCompany.getLoginName(), Encodes.encodeMd5(webUserForCompany.getPassword()));
		
		//判断该用户是否为空
		if(CommonUtil.isNull(webUserForCompany)){
			map.put("status", CommonUtil.FAIL);
			map.put("message", "用户不存在，请检查用户名和密码再登录!");
		}else{
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "登录成功");
			map.put("data", webUserForCompany);
		}
		
		return map;	
	}
	
	/**
	 * 注册网上用户（个人）
	 * @param webUserForPerson
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/registerForPerson")
	public Map<String,Object> registerForPerson(@RequestBody WebUserForPerson webUserForPerson){
		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			//默认记录创建时间为现在
			webUserForPerson.setRecordCreateTime(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm_ss));
			webUserForPerson.setPassword(Encodes.encodeMd5(webUserForPerson.getPassword()));
			webUserForPerson.setFirstPinYin(PinyinToolkit.cn2FirstSpell(webUserForPerson.getUserName()));
			webUserForPerson.setAllPinYin(PinyinToolkit.cn2Spell(webUserForPerson.getUserName()));
			webUserForPerson.setRegisterDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd));
			webUserForPerson.setEnable("0");
			//根据邀请码获取邀请码ID
			InvitationCode invitationCode = invitationCodeService.getInvitationCodeByCode(webUserForPerson.getCode());
			if(!CommonUtil.isNull(invitationCode)){
				webUserForPerson.setInvitationCodeId(invitationCode.getId());
			}else{
				map.put("status", CommonUtil.ERROR);
				map.put("message", "邀请码不能为空！");
				return map;
			}
			webUserForPersonService.addWebUserForPerson(webUserForPerson);			
			//注册成功以后，清除session里面的手机验证码
			RequestContextHolderUtil.getSession().removeAttribute(webUserForPerson.getTel());
			//注册成功过后将邀请码修改为已使用
			invitationCode.setEnable("1");
			invitationCodeService.updateInvitationCode(invitationCode);
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "注册成功");
			return map;
		} catch (Exception e) {
			map.put("status", CommonUtil.FAIL);
			map.put("message", "注册失败");
			return map;
		}
	}
	@ResponseBody
	@RequestMapping("/registerForCompany")
	public Map<String,Object> registerForCompany(@RequestBody WebUserForCompany webUserForCompany){
		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			//默认记录创建时间为现在
			webUserForCompany.setRecordCreateTime(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd_HH_mm_ss));
			webUserForCompany.setPassword(Encodes.encodeMd5(webUserForCompany.getPassword()));
			webUserForCompany.setFirstCompanyPy(PinyinToolkit.cn2FirstSpell(webUserForCompany.getCompanyName()));
			webUserForCompany.setAllCompanyPy(PinyinToolkit.cn2Spell(webUserForCompany.getCompanyName()));
			webUserForCompany.setFirstLegalPersonPy(webUserForCompany.getLegalPerson());
			webUserForCompany.setAllLegalPersonPy(webUserForCompany.getLegalPerson());
			webUserForCompany.setRegisterDate(DateTimeUtil.getNowDateStr(DateTimeUtil.yyyy_MM_dd));
			webUserForCompany.setEnable("0");
			//企业用户
			webUserForCompany.setType("1");
			
			InvitationCode invitationCode = null;
			//判断邀请码是否为空
			if(!CommonUtil.isNull(webUserForCompany.getCode())){
				//根据邀请码获取邀请码ID
				invitationCode = invitationCodeService.getInvitationCodeByCode(webUserForCompany.getCode());
				if(!CommonUtil.isNull(invitationCode)){
					webUserForCompany.setInvitationCodeId(invitationCode.getId());
				}
			}
			webUserForCompanyService.addWebUserForCompany(webUserForCompany);			
			//注册成功以后，清除session里面的手机验证码
			RequestContextHolderUtil.getSession().removeAttribute(webUserForCompany.getTel());
			if(!CommonUtil.isNull(invitationCode)){
				//注册成功过后将邀请码修改为已使用
				invitationCode.setEnable("1");
				invitationCodeService.updateInvitationCode(invitationCode);
			}
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "注册成功");
			return map;
		} catch (Exception e) {
			map.put("status", CommonUtil.FAIL);
			map.put("message", "注册失败");
			return map;
		}
	}
	
	/**
	 * 发送手机验证码
	 * 
	 * @param session
	 * @param tel
	 */
	@ResponseBody
	@RequestMapping("/addPhoneRandCode")
	public void addPhoneRandCode(HttpSession session,TempVo tempVo) {
		//获取6位随机验证码
		String randCode = StringUtil.createRandom(false, 6);
		//手机发送的短信内容
		String msgContent = "您的验证码是：" + randCode+"。验证码有效期为1个小时。";
		// 发送短信
		phoneMsgService.saveMsg(tempVo.getTel(), msgContent);
		
		// 把手机验证码存入session（以手机号码作为唯一key）
		session.setAttribute(tempVo.getTel(), randCode);
	}
	
	/**
	 * 验证手机号的唯一性
	 * @param webUserForPerson
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/validatePhone")
	public Map<String,Object> validatePhone(@RequestBody WebUserForPerson webUserForPerson){
		
		Map<String,Object> map = new HashMap<String,Object>();
		//验证手机号是否为空
		if(CommonUtil.isNull(webUserForPerson.getTel())){
			
			map.put("status", CommonUtil.ERROR);
			map.put("message", "手机号不能为空！");
			return map;
		}
		
		//验证手机号的唯一性
		boolean b = webService.validatePhone(webUserForPerson.getTel());
		if(b){
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "手机号可以使用");
			return map;
		}else{
			map.put("status", CommonUtil.FAIL);
			map.put("message", "手机号已经被注册！");
			return map;
		}
	}
	
	/**
	 * 验证邀请码是否可用
	 * @param webUserForPerson
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/validateInvitationCode")
	public Map<String,Object> validateInvitationCode(@RequestBody WebUserForPerson webUserForPerson){
		
		Map<String,Object> map = new HashMap<String,Object>();
		//验证邀请码是否为空
		if(CommonUtil.isNull(webUserForPerson.getCode())){
			
			map.put("status", CommonUtil.ERROR);
			map.put("message", "邀请码不能为空");
			return map;
		}
		
		//验证邀请码是否可用
		boolean b = invitationCodeService.validateInvitationCode(webUserForPerson.getCode());
		if(b){
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "邀请码可用");
			return map;
		}else{
			map.put("status", CommonUtil.FAIL);
			map.put("message", "邀请码已经被使用或该邀请码不存在");
			return map;
		}
	}
	
	/**
	 * 验证登录名是否已经被使用
	 * @param webUserForPerson
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/validateLoginName")
	public Map<String,Object> validateLoginName(@RequestBody WebUserForPerson webUserForPerson){
		
		Map<String,Object> map = new HashMap<String,Object>();
		//判断登录名是否为空
		if(CommonUtil.isNull(webUserForPerson.getLoginName())){
			map.put("status", CommonUtil.ERROR);
			map.put("message", "登录名不能为空！");
			return map;
		}
		
		boolean b = webService.validateLoginNameByPerson(webUserForPerson.getLoginName());
		if(b){
			map.put("status", CommonUtil.SUCCESS);
			map.put("message", "登录名可用");
			return map;
		}else{
			map.put("status", CommonUtil.FAIL);
			map.put("message", "登录名已经被使用！");
			return map;
		}
	}
}
